package coordinator

import (
	"adai.design/homemaster/container/accessory"
	"adai.design/homemaster/container/characteristic"
	"adai.design/homemaster/log"
	"encoding/binary"
	"encoding/hex"
	"github.com/gorilla/websocket"
)

// SmartPlug

type zigbeeSmartPlug struct {
	*ZigbeeDescriptor
	acc *accessory.Outlet
}

func (z *zigbeeSmartPlug) update(data []byte) error {
	srcAddr := binary.BigEndian.Uint16(data[1:])
	endpoint := data[3]

	var value byte
	if len(data) < 11 {
		value = data[7]
	} else {
		value = data[11]
	}

	attributeId := binary.BigEndian.Uint16(data[6:8])
	if attributeId != 0x0000 {
		return nil
	}

	log.Printf("attribute: netaddr(%04x) endpoint(%d) data(%d)\n", srcAddr, endpoint, value)
	if endpoint == 0x01 {
		if value == 0x01 {
			z.acc.Outlet.Switch.UpdateValue(characteristic.SwitchStateOn)
		} else {
			z.acc.Outlet.Switch.UpdateValue(characteristic.SwitchStateOff)
		}
	}
	return nil
}

func (z *zigbeeSmartPlug) onValueUpdate(value uint8, channel uint8) {
	data := make([]byte, 6)
	data[0] = 0x02
	netAddr, _ := hex.DecodeString(z.NetAddr)
	copy(data[1:], netAddr)
	data[3] = 0x01
	data[4] = channel
	data[5] = value
	msg := &Message{MsgT: SerialLinkMsgTypeOnOffNoEffects, Data: data}
	sdata, err := msg.Encode()
	if err != nil {
		log.Fatal(err)
	}
	client.task <- sdata
}

func newZigbeeSmartPlug(zigbee *ZigbeeDescriptor) *zigbeeSmartPlug {
	plug := &zigbeeSmartPlug{
		ZigbeeDescriptor: zigbee,
		acc:              accessory.NewOutlet(zigbee.MacAddr),
	}

	plug.acc.Outlet.Switch.OnValueUpdateFromConn(func(conn *websocket.Conn, c *characteristic.Characteristic, newValue, oldValue interface{}) {
		if newValue == characteristic.SwitchStateOn {
			plug.onValueUpdate(1, 1)
		} else {
			plug.onValueUpdate(0, 1)
		}
	})
	return plug
}
